package top.ninwoo.cloudcenter.register;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ZookeeperConfiguration {

    private static final Logger LOG = LoggerFactory.getLogger(ZookeeperConfiguration.class);

    @Value("${zookeeper.url}")
    private String url;

    @Bean(destroyMethod = "close")
    public CuratorFramework zkClient() {
        ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(url, retryPolicy);
        try {
            LOG.info("Zookeeper客户端[{}]已经连接", url);
            client.start();
        } catch (Exception e) {
            LOG.error("Zookeeper客户端[{}]连接失败", url);
            e.printStackTrace();
        }
        return client;
    }
}
